/**
 * UI管理类
 * 负责管理用户界面的渲染和交互
 */

export class UIManager {
    constructor(state) {
        this.state = state;
        this.events = {};
        this.currentFileView = 'main.c';
    }

    init() {
        console.log('UI Manager 初始化开始');
        this.renderApp();
        this.bindEvents();
        console.log('UI Manager 初始化完成');
    }

    // 渲染整个应用
    renderApp() {
        console.log('开始渲染应用');
        const app = document.getElementById('app');
        if (app) {
            app.innerHTML = this.getAppTemplate();
            console.log('应用模板渲染完成');
        } else {
            console.error('未找到 #app 元素');
        }
        this.renderModalContainer();
    }

    // 获取应用模板
    getAppTemplate() {
        return `
            <!-- 头部 -->
            <header class="text-center mb-12">
                <h1 class="text-4xl md:text-5xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-blue-400 to-purple-500 py-4">
                    <i class="fas fa-microchip mr-3"></i>ESP32 开发辅助工具
                </h1>
                <p class="text-gray-300 max-w-2xl mx-auto">
                    一站式ESP32项目初始化工具，从配置到代码生成，再到设备烧录，全流程支持
                </p>
            </header>

            <!-- 安全提示 -->
            <div class="bg-yellow-900 border-l-4 border-yellow-500 p-4 rounded mb-8">
                <div class="flex">
                    <div class="flex-shrink-0">
                        <i class="fas fa-exclamation-triangle text-yellow-500 text-xl"></i>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm text-yellow-300">
                            <strong>重要安全提示：</strong>现代浏览器和操作系统可能会阻止下载的文件。
                            如果遇到此问题，请尝试以下方法：
                            <ol class="list-decimal pl-5 mt-2 space-y-1">
                                <li>点击下载后选择"保留"或"允许"</li>
                                <li>在下载管理器中恢复被阻止的文件</li>
                                <li>使用"导出为文本"备选方案</li>
                                <li>检查杀毒软件隔离区并恢复文件</li>
                            </ol>
                        </p>
                    </div>
                </div>
            </div>

            <!-- 主要功能区域 -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
                <!-- 左侧配置区域 -->
                <div class="space-y-8">
                    <!-- 项目配置区 -->
                    <div class="bg-gray-800 rounded-xl shadow-2xl p-6 border border-gray-700 transition-all hover:border-indigo-500">
                        <div class="flex items-center mb-4">
                            <i class="fas fa-cog text-indigo-400 text-xl mr-3"></i>
                            <h2 class="text-xl font-semibold">项目配置</h2>
                        </div>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <!-- 芯片型号选择 -->
                            <div>
                                <label class="block text-sm font-medium text-gray-300 mb-2">芯片型号</label>
                                <select id="chip-selector" class="w-full bg-gray-700 border border-gray-600 rounded-lg py-2 px-3 text-white focus:outline-none focus:ring-2 focus:ring-indigo-500">
                                    <option value="ESP32-WROOM-32">ESP32-WROOM-32</option>
                                    <option value="ESP32-C3-MINI-1">ESP32-C3-MINI-1</option>
                                    <option value="ESP32-S3">ESP32-S3</option>
                                    <option value="ESP32-PICO">ESP32-PICO</option>
                                </select>
                            </div>
                            
                            <!-- 项目名称 -->
                            <div>
                                <label class="block text-sm font-medium text-gray-300 mb-2">项目名称</label>
                                <input type="text" id="project-name" value="esp32_project" class="w-full bg-gray-700 border border-gray-600 rounded-lg py-2 px-3 text-white focus:outline-none focus:ring-2 focus:ring-indigo-500">
                            </div>
                            
                            <!-- 功能模块配置 -->
                            <div class="md:col-span-2">
                                <label class="block text-sm font-medium text-gray-300 mb-2">功能模块</label>
                                <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
                                    <div class="flex items-center bg-gray-700 rounded-lg p-3">
                                        <input type="checkbox" id="wifi-enable" class="rounded bg-gray-600 border-gray-600 text-indigo-600 focus:ring-indigo-500">
                                        <label for="wifi-enable" class="ml-2 block text-sm">WiFi</label>
                                    </div>
                                    <div class="flex items-center bg-gray-700 rounded-lg p-3">
                                        <input type="checkbox" id="bluetooth-enable" class="rounded bg-gray-600 border-gray-600 text-indigo-600 focus:ring-indigo-500">
                                        <label for="bluetooth-enable" class="ml-2 block text-sm">蓝牙</label>
                                    </div>
                                    <div class="flex items-center bg-gray-700 rounded-lg p-3">
                                        <input type="checkbox" id="http-server-enable" class="rounded bg-gray-600 border-gray-600 text-indigo-600 focus:ring-indigo-500">
                                        <label for="http-server-enable" class="ml-2 block text-sm">HTTP服务器</label>
                                    </div>
                                    <div class="flex items-center bg-gray-700 rounded-lg p-3">
                                        <input type="checkbox" id="ota-enable" class="rounded bg-gray-600 border-gray-600 text-indigo-600 focus:ring-indigo-500">
                                        <label for="ota-enable" class="ml-2 block text-sm">OTA更新</label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 可视化配置界面 -->
                    <div class="bg-gray-800 rounded-xl shadow-2xl p-6 border border-gray-700 transition-all hover:border-indigo-500">
                        <div class="flex items-center mb-4">
                            <i class="fas fa-microchip text-indigo-400 text-xl mr-3"></i>
                            <h2 class="text-xl font-semibold">引脚配置</h2>
                        </div>
                        <div id="pin-configuration" class="border-2 border-dashed border-gray-600 rounded-lg p-4 text-center min-h-[200px] flex items-center justify-center">
                            <p class="text-gray-400">选择芯片型号以加载引脚图</p>
                        </div>
                    </div>
                    
                    <!-- 项目文件管理区 -->
                    <div class="bg-gray-800 rounded-xl shadow-2xl p-6 border border-gray-700 transition-all hover:border-indigo-500">
                        <div class="flex items-center mb-4">
                            <i class="fas fa-folder-tree text-indigo-400 text-xl mr-3"></i>
                            <h2 class="text-xl font-semibold">项目结构</h2>
                        </div>
                        <div id="file-structure" class="border border-gray-700 rounded-lg p-4 bg-gray-900 min-h-[150px]">
                            <p class="text-gray-400 text-center">生成代码后将显示项目文件结构</p>
                        </div>
                        <div class="mt-4 flex space-x-3">
                            <button id="download-zip" class="flex-1 bg-gradient-to-r from-green-500 to-emerald-600 text-white py-2 px-4 rounded-lg hover:opacity-90 transition flex items-center justify-center">
                                <i class="fas fa-download mr-2"></i>下载项目
                            </button>
                            <button id="export-text" class="flex-1 bg-gradient-to-r from-blue-500 to-cyan-600 text-white py-2 px-4 rounded-lg hover:opacity-90 transition flex items-center justify-center">
                                <i class="fas fa-copy mr-2"></i>复制结构
                            </button>
                        </div>
                        <div class="mt-3 text-xs text-gray-400">
                            <p><i class="fas fa-info-circle mr-1"></i>如果下载被阻止，可使用"导出为文本"功能</p>
                        </div>
                    </div>
                </div>
                
                <!-- 右侧代码和设备区域 -->
                <div class="space-y-8">
                    <!-- 代码生成区 -->
                    <div class="bg-gray-800 rounded-xl shadow-2xl p-6 border border-gray-700 transition-all hover:border-indigo-500 h-full flex flex-col">
                        <div class="flex items-center justify-between mb-4">
                            <div class="flex items-center">
                                <i class="fas fa-code text-indigo-400 text-xl mr-3"></i>
                                <h2 class="text-xl font-semibold">代码预览</h2>
                            </div>
                            <button id="generate-code" class="bg-gradient-to-r from-indigo-500 to-purple-600 text-white py-1 px-4 rounded-lg hover:opacity-90 transition text-sm flex items-center">
                                <i class="fas fa-bolt mr-2"></i>重新生成
                            </button>
                        </div>
                        <div class="flex space-x-2 mb-3 overflow-x-auto">
                            <button class="tab-btn active text-sm py-1 px-3 rounded bg-gray-700" data-file="main.c">main.c</button>
                            <button class="tab-btn text-sm py-1 px-3 rounded bg-gray-700" data-file="CMakeLists.txt">CMakeLists.txt</button>
                            <button class="tab-btn text-sm py-1 px-3 rounded bg-gray-700" data-file="sdkconfig">sdkconfig</button>
                        </div>
                        <div id="code-preview" class="flex-grow border border-gray-700 rounded-lg overflow-auto max-h-[400px] bg-gray-900">
                            <pre class="m-0 !bg-gray-900"><code class="language-c">/* 生成的代码将在此显示 */</code></pre>
                        </div>
                    </div>
                    
                    <!-- 设备交互区 -->
                    <div class="bg-gray-800 rounded-xl shadow-2xl p-6 border border-gray-700 transition-all hover:border-indigo-500">
                        <div class="flex items-center mb-4">
                            <i class="fas fa-plug text-indigo-400 text-xl mr-3"></i>
                            <h2 class="text-xl font-semibold">设备交互</h2>
                        </div>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div class="space-y-4">
                                <button id="connect-device" class="w-full bg-gradient-to-r from-blue-500 to-indigo-600 text-white py-3 px-4 rounded-lg hover:opacity-90 transition flex items-center justify-center">
                                    <i class="fas fa-link mr-2"></i>连接设备
                                </button>
                                <div id="connection-status" class="text-center py-3 rounded-lg bg-gray-700 flex items-center justify-center">
                                    <span class="status-indicator status-disconnected mr-2"></span>
                                    <span>未连接设备</span>
                                </div>
                            </div>
                            <div class="space-y-4">
                                <input type="file" id="firmware-file" accept=".bin" class="hidden">
                                <button id="select-firmware" class="w-full bg-gradient-to-r from-purple-500 to-pink-600 text-white py-3 px-4 rounded-lg hover:opacity-90 transition flex items-center justify-center">
                                    <i class="fas fa-file-import mr-2"></i>选择固件
                                </button>
                                <button id="flash-firmware" class="w-full bg-gradient-to-r from-red-500 to-orange-600 text-white py-3 px-4 rounded-lg hover:opacity-90 transition flex items-center justify-center" disabled>
                                    <i class="fas fa-burn mr-2"></i>烧录固件
                                </button>
                            </div>
                        </div>
                        <div class="mt-6">
                            <div class="flex justify-between mb-1">
                                <span class="text-sm font-medium">烧录进度</span>
                                <span id="progress-percent" class="text-sm font-medium">0%</span>
                            </div>
                            <div class="w-full bg-gray-700 rounded-full h-2.5">
                                <div id="flash-progress" class="bg-gradient-to-r from-green-400 to-emerald-500 h-2.5 rounded-full transition-all duration-300" style="width: 0%"></div>
                            </div>
                        </div>
                        <div class="mt-4">
                            <label class="block text-sm font-medium text-gray-300 mb-2">串口监控</label>
                            <div id="serial-monitor" class="border border-gray-700 rounded-lg p-3 bg-gray-900 h-32 overflow-y-auto text-sm font-mono">
                                <p class="text-gray-400">设备连接后将显示串口信息...</p>
                            </div>
                            <div class="flex mt-2 space-x-2">
                                <input type="text" id="serial-command" placeholder="输入命令..." class="flex-1 bg-gray-700 border border-gray-600 rounded-lg py-2 px-3 text-white text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500">
                                <button id="send-command" class="bg-gray-700 hover:bg-gray-600 text-white py-2 px-4 rounded-lg text-sm transition">发送</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 底部信息 -->
            <footer class="text-center text-gray-400 text-sm mt-8 pt-6 border-t border-gray-800">
                <p>ESP32 开发辅助工具 &copy; 2023 - 简化您的嵌入式开发流程</p>
            </footer>
        `;
    }

    // 渲染模态框容器
    renderModalContainer() {
        const modalContainer = document.getElementById('modal-container');
        if (modalContainer) {
            modalContainer.innerHTML = `
                <!-- 引脚配置模态框 -->
                <div id="pin-config-modal" class="pin-config-overlay hidden fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50">
                    <div class="pin-config-panel bg-gray-800 rounded-xl shadow-2xl p-6 w-full max-w-md border border-gray-700">
                        <div class="flex justify-between items-center mb-4">
                            <h3 class="text-xl font-semibold">配置引脚</h3>
                            <button id="close-modal" class="text-gray-400 hover:text-white">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                        <div class="mb-6">
                            <p class="text-gray-300 mb-4">配置 <span id="current-pin" class="font-mono bg-gray-700 px-2 py-1 rounded">GPIO0</span> 引脚</p>
                            <label class="block text-sm font-medium text-gray-300 mb-2">引脚模式</label>
                            <select id="pin-mode" class="w-full bg-gray-700 border border-gray-600 rounded-lg py-2 px-3 text-white focus:outline-none focus:ring-2 focus:ring-indigo-500">
                                <option value="input">输入 (Input)</option>
                                <option value="output">输出 (Output)</option>
                                <option value="pwm">脉宽调制 (PWM)</option>
                                <option value="adc">模数转换 (ADC)</option>
                                <option value="uart">串口通信 (UART)</option>
                                <option value="i2c">I2C总线</option>
                                <option value="spi">SPI总线</option>
                            </select>
                        </div>
                        <div class="flex justify-end space-x-3">
                            <button id="cancel-pin-config" class="px-4 py-2 border border-gray-600 rounded-lg text-gray-300 hover:bg-gray-700 transition">取消</button>
                            <button id="save-pin-config" class="px-4 py-2 bg-gradient-to-r from-indigo-500 to-purple-600 text-white rounded-lg hover:opacity-90 transition">保存配置</button>
                        </div>
                    </div>
                </div>
            `;
        }
    }

    // 绑定事件
    bindEvents() {
        // 芯片选择
        const chipSelector = document.getElementById('chip-selector');
        if (chipSelector) {
            chipSelector.addEventListener('change', (e) => {
                this.emit('chipChange', e.target.value);
            });
        }

        // 项目名称
        const projectName = document.getElementById('project-name');
        if (projectName) {
            projectName.addEventListener('input', (e) => {
                this.emit('projectNameChange', e.target.value);
            });
        }

        // 功能开关
        const wifiEnable = document.getElementById('wifi-enable');
        const bluetoothEnable = document.getElementById('bluetooth-enable');
        const httpServerEnable = document.getElementById('http-server-enable');
        const otaEnable = document.getElementById('ota-enable');

        const featureToggles = [
            { element: wifiEnable, key: 'wifi' },
            { element: bluetoothEnable, key: 'bluetooth' },
            { element: httpServerEnable, key: 'httpServer' },
            { element: otaEnable, key: 'ota' }
        ];

        featureToggles.forEach(({ element, key }) => {
            if (element) {
                element.addEventListener('change', () => {
                    const features = {};
                    featureToggles.forEach(({ element, key }) => {
                        features[key] = element.checked;
                    });
                    this.emit('featureToggle', features);
                });
            }
        });

        // 生成代码按钮
        const generateCodeBtn = document.getElementById('generate-code');
        if (generateCodeBtn) {
            generateCodeBtn.addEventListener('click', () => {
                this.emit('generateCode');
            });
        }

        // 下载项目按钮
        const downloadZipBtn = document.getElementById('download-zip');
        if (downloadZipBtn) {
            downloadZipBtn.addEventListener('click', () => {
                this.emit('downloadProject');
            });
        }

        // 导出文本按钮
        const exportTextBtn = document.getElementById('export-text');
        if (exportTextBtn) {
            exportTextBtn.addEventListener('click', () => {
                this.emit('exportText');
            });
        }

        // 连接设备按钮
        const connectDeviceBtn = document.getElementById('connect-device');
        if (connectDeviceBtn) {
            connectDeviceBtn.addEventListener('click', () => {
                const isConnected = connectDeviceBtn.textContent.includes('断开');
                if (isConnected) {
                    this.emit('disconnectDevice');
                } else {
                    this.emit('connectDevice');
                }
            });
        }

        // 选择固件按钮
        const selectFirmwareBtn = document.getElementById('select-firmware');
        const firmwareFileInput = document.getElementById('firmware-file');
        if (selectFirmwareBtn && firmwareFileInput) {
            selectFirmwareBtn.addEventListener('click', () => {
                firmwareFileInput.click();
            });

            firmwareFileInput.addEventListener('change', (e) => {
                if (e.target.files.length > 0) {
                    const flashFirmwareBtn = document.getElementById('flash-firmware');
                    if (flashFirmwareBtn) {
                        flashFirmwareBtn.disabled = false;
                    }
                }
            });
        }

        // 烧录固件按钮
        const flashFirmwareBtn = document.getElementById('flash-firmware');
        if (flashFirmwareBtn) {
            flashFirmwareBtn.addEventListener('click', () => {
                if (firmwareFileInput && firmwareFileInput.files.length > 0) {
                    this.emit('flashFirmware', firmwareFileInput.files[0]);
                }
            });
        }

        // 模态框事件
        const closeModalBtn = document.getElementById('close-modal');
        const cancelPinConfigBtn = document.getElementById('cancel-pin-config');
        const savePinConfigBtn = document.getElementById('save-pin-config');

        if (closeModalBtn) {
            closeModalBtn.addEventListener('click', () => this.closePinConfigModal());
        }

        if (cancelPinConfigBtn) {
            cancelPinConfigBtn.addEventListener('click', () => this.closePinConfigModal());
        }

        if (savePinConfigBtn) {
            savePinConfigBtn.addEventListener('click', () => {
                const pin = this.currentPin;
                const mode = document.getElementById('pin-mode').value;
                if (pin !== null) {
                    this.emit('pinConfig', pin, mode);
                    this.closePinConfigModal();
                }
            });
        }

        // 标签页切换
        const tabButtons = document.querySelectorAll('.tab-btn');
        tabButtons.forEach(btn => {
            btn.addEventListener('click', () => {
                // 更新激活状态
                tabButtons.forEach(b => b.classList.remove('active'));
                btn.classList.add('active');

                // 获取文件名
                const fileName = btn.getAttribute('data-file');
                this.currentFileView = fileName;

                // 更新代码预览
                const files = this.state.getProjectFiles();
                const content = files[`main/${fileName}`] || files[fileName] || `/* ${fileName} 文件内容 */`;
                this.updateCodePreview(content);
            });
        });
    }

    // 打开引脚配置模态框
    openPinConfigModal(pin) {
        this.currentPin = pin;
        const modal = document.getElementById('pin-config-modal');
        const currentPinEl = document.getElementById('current-pin');
        const pinModeEl = document.getElementById('pin-mode');

        if (modal && currentPinEl && pinModeEl) {
            // 更新当前引脚显示
            currentPinEl.textContent = `GPIO${pin}`;
            
            // 设置当前引脚的配置值
            const pinConfig = this.state.getPinConfigurations()[pin];
            if (pinConfig) {
                pinModeEl.value = pinConfig.mode;
            } else {
                pinModeEl.value = 'output'; // 默认值为输出模式
            }

            // 显示模态框
            modal.classList.remove('hidden');
            
            // 阻止背景滚动
            document.body.style.overflow = 'hidden';
        }
    }

    // 关闭引脚配置模态框
    closePinConfigModal() {
        const modal = document.getElementById('pin-config-modal');
        if (modal) {
            modal.classList.add('hidden');
        }
        this.currentPin = null;
    }

    // 更新引脚图
    updatePinDiagram() {
        const pinConfiguration = document.getElementById('pin-configuration');
        if (!pinConfiguration) return;

        const chipModel = this.state.getChipModel();
        const pinConfigurations = this.state.getPinConfigurations();

        let pinDiagramHTML = '';

        if (chipModel === 'ESP32-WROOM-32') {
            pinDiagramHTML = `
                <div class="text-center">
                    <h3 class="text-lg font-semibold mb-4">ESP32-WROOM-32 引脚图</h3>
                    <div class="grid grid-cols-4 gap-2 max-w-md mx-auto">
                        ${Array.from({length: 24}, (_, i) => {
                            const pinConfig = pinConfigurations[i];
                            const configuredClass = pinConfig ? 'pin-configured border-purple-500' : 'border-gray-600';
                            return `
                                <div class="p-2 border rounded-lg cursor-pointer hover:bg-indigo-900 transition pin-item ${configuredClass}" 
                                     data-pin="${i}" onclick="window.esp32DevTool.openPinConfigModal(${i})">
                                    <div class="font-medium">GPIO${i}</div>
                                    <div class="text-xs text-gray-400">${pinConfig ? pinConfig.mode : '未配置'}</div>
                                </div>
                            `;
                        }).join('')}
                    </div>
                </div>
            `;
        } else if (chipModel === 'ESP32-C3-MINI-1') {
            pinDiagramHTML = `
                <div class="text-center">
                    <h3 class="text-lg font-semibold mb-4">ESP32-C3-MINI-1 引脚图</h3>
                    <div class="grid grid-cols-4 gap-2 max-w-md mx-auto">
                        ${Array.from({length: 18}, (_, i) => {
                            const pinConfig = pinConfigurations[i];
                            const configuredClass = pinConfig ? 'pin-configured border-purple-500' : 'border-gray-600';
                            return `
                                <div class="p-2 border rounded-lg cursor-pointer hover:bg-indigo-900 transition pin-item ${configuredClass}" 
                                     data-pin="${i}" onclick="window.esp32DevTool.openPinConfigModal(${i})">
                                    <div class="font-medium">GPIO${i}</div>
                                    <div class="text-xs text-gray-400">${pinConfig ? pinConfig.mode : '未配置'}</div>
                                </div>
                            `;
                        }).join('')}
                    </div>
                </div>
            `;
        } else if (chipModel === 'ESP32-S3') {
            pinDiagramHTML = `
                <div class="text-center">
                    <h3 class="text-lg font-semibold mb-4">ESP32-S3 引脚图</h3>
                    <div class="grid grid-cols-4 gap-2 max-w-md mx-auto">
                        ${Array.from({length: 32}, (_, i) => {
                            const pinConfig = pinConfigurations[i];
                            const configuredClass = pinConfig ? 'pin-configured border-purple-500' : 'border-gray-600';
                            return `
                                <div class="p-2 border rounded-lg cursor-pointer hover:bg-indigo-900 transition pin-item ${configuredClass}" 
                                     data-pin="${i}" onclick="window.esp32DevTool.openPinConfigModal(${i})">
                                    <div class="font-medium">GPIO${i}</div>
                                    <div class="text-xs text-gray-400">${pinConfig ? pinConfig.mode : '未配置'}</div>
                                </div>
                            `;
                        }).join('')}
                    </div>
                </div>
            `;
        } else {
            pinDiagramHTML = `
                <div class="text-center">
                    <h3 class="text-lg font-semibold mb-4">${chipModel} 引脚图</h3>
                    <div class="grid grid-cols-4 gap-2 max-w-md mx-auto">
                        ${Array.from({length: 12}, (_, i) => {
                            const pinConfig = pinConfigurations[i];
                            const configuredClass = pinConfig ? 'pin-configured border-purple-500' : 'border-gray-600';
                            return `
                                <div class="p-2 border rounded-lg cursor-pointer hover:bg-indigo-900 transition pin-item ${configuredClass}" 
                                     data-pin="${i}" onclick="window.esp32DevTool.openPinConfigModal(${i})">
                                    <div class="font-medium">GPIO${i}</div>
                                    <div class="text-xs text-gray-400">${pinConfig ? pinConfig.mode : '未配置'}</div>
                                </div>
                            `;
                        }).join('')}
                    </div>
                </div>
            `;
        }

        pinConfiguration.innerHTML = pinDiagramHTML;
    }

    // 更新代码预览
    updateCodePreview(code) {
        const codePreview = document.getElementById('code-preview');
        if (codePreview) {
            codePreview.innerHTML = `<pre class="m-0 !bg-gray-900"><code class="language-c">${this.escapeHtml(code || '')}</code></pre>`;
            Prism.highlightAll();
        }
    }

    // 更新文件结构
    updateFileStructure() {
        const fileStructure = document.getElementById('file-structure');
        if (!fileStructure) return;

        const files = this.state.getProjectFiles();
        const projectName = this.state.getProjectName();
        const features = this.state.getFeatures();

        if (Object.keys(files).length === 0) {
            fileStructure.innerHTML = '<p class="text-gray-400 text-center">生成代码后将显示项目文件结构</p>';
            return;
        }

        let structureHtml = `
        <div class="tree text-gray-300">
            <ul>
                <li>${projectName}/
                    <ul>
                        <li><i class="fas fa-file-alt text-blue-400 mr-1"></i> CMakeLists.txt</li>
                        <li><i class="fas fa-file-alt text-blue-400 mr-1"></i> sdkconfig</li>
        `;

        if (features.ota) {
            structureHtml += `<li><i class="fas fa-file-alt text-blue-400 mr-1"></i> partitions.csv</li>`;
        }

        structureHtml += `
                        <li class="mt-1">main/
                            <ul>
                                <li><i class="fas fa-file-code text-green-400 mr-1"></i> main.c</li>
                            </ul>
                        </li>
        `;

        // 检查是否有特殊组件
        const pinConfigs = this.state.getPinConfigurations();
        let hasSpecialComponents = false;
        for (const pin in pinConfigs) {
            const config = pinConfigs[pin];
            if (['pwm', 'adc', 'uart', 'i2c', 'spi'].includes(config.mode)) {
                hasSpecialComponents = true;
                break;
            }
        }

        if (hasSpecialComponents || features.httpServer || features.ota) {
            structureHtml += `
                        <li class="mt-1">components/
                            <ul>
                                <li><i class="fas fa-folder text-yellow-400 mr-1"></i> ...</li>
                            </ul>
                        </li>
            `;
        }

        structureHtml += `
                    </ul>
                </li>
            </ul>
        </div>`;

        fileStructure.innerHTML = structureHtml;
    }

    // 更新连接状态
    updateConnectionStatus(connected) {
        const connectionStatus = document.getElementById('connection-status');
        const connectDeviceBtn = document.getElementById('connect-device');
        
        if (connectionStatus) {
            const statusIndicator = connectionStatus.querySelector('.status-indicator');
            if (statusIndicator) {
                statusIndicator.classList.remove(connected ? 'status-disconnected' : 'status-connected');
                statusIndicator.classList.add(connected ? 'status-connected' : 'status-disconnected');
            }
            connectionStatus.innerHTML = connected 
                ? '<span class="status-indicator status-connected"></span>已连接设备'
                : '<span class="status-indicator status-disconnected"></span>未连接设备';
        }

        if (connectDeviceBtn) {
            if (connected) {
                connectDeviceBtn.innerHTML = '<i class="fas fa-unlink mr-2"></i>断开连接';
                connectDeviceBtn.classList.remove('bg-gradient-to-r', 'from-blue-500', 'to-indigo-600');
                connectDeviceBtn.classList.add('bg-gradient-to-r', 'from-red-500', 'to-orange-600');
            } else {
                connectDeviceBtn.innerHTML = '<i class="fas fa-link mr-2"></i>连接设备';
                connectDeviceBtn.classList.remove('bg-gradient-to-r', 'from-red-500', 'to-orange-600');
                connectDeviceBtn.classList.add('bg-gradient-to-r', 'from-blue-500', 'to-indigo-600');
            }
        }

        // 更新烧录按钮状态
        const flashFirmwareBtn = document.getElementById('flash-firmware');
        if (flashFirmwareBtn) {
            flashFirmwareBtn.disabled = !connected;
        }
    }

    // 显示提示信息
    showAlert(message, type = 'info') {
        // 在串口监视器中显示消息
        const serialMonitor = document.getElementById('serial-monitor');
        if (serialMonitor) {
            const timestamp = new Date().toLocaleTimeString();
            const messageElement = document.createElement('p');
            
            // 根据消息类型设置样式
            switch(type) {
                case 'error':
                    messageElement.className = 'serial-error';
                    break;
                case 'success':
                    messageElement.className = 'serial-success';
                    break;
                case 'info':
                    messageElement.className = 'serial-info';
                    break;
                default:
                    messageElement.className = 'serial-message';
            }
            
            messageElement.textContent = `[${timestamp}] ${message}`;
            serialMonitor.appendChild(messageElement);
            
            // 滚动到底部
            serialMonitor.scrollTop = serialMonitor.scrollHeight;
        }

        // 显示浏览器通知（如果用户允许）
        if (type === 'success' || type === 'error') {
            if ('Notification' in window && Notification.permission === 'granted') {
                new Notification(`ESP32工具 - ${type === 'success' ? '成功' : '错误'}`, {
                    body: message,
                    icon: type === 'success' ? '✅' : '❌'
                });
            }
        }
    }

    // 加载配置到UI
    loadConfig(config) {
        const chipSelector = document.getElementById('chip-selector');
        const projectName = document.getElementById('project-name');
        const wifiEnable = document.getElementById('wifi-enable');
        const bluetoothEnable = document.getElementById('bluetooth-enable');
        const httpServerEnable = document.getElementById('http-server-enable');
        const otaEnable = document.getElementById('ota-enable');

        if (chipSelector) chipSelector.value = config.chipModel || 'ESP32-WROOM-32';
        if (projectName) projectName.value = config.projectName || 'esp32_project';
        if (wifiEnable) wifiEnable.checked = config.features?.wifi || false;
        if (bluetoothEnable) bluetoothEnable.checked = config.features?.bluetooth || false;
        if (httpServerEnable) httpServerEnable.checked = config.features?.httpServer || false;
        if (otaEnable) otaEnable.checked = config.features?.ota || false;

        this.updatePinDiagram();
    }

    // 事件发射器
    emit(event, data) {
        if (this.events[event]) {
            this.events[event].forEach(callback => callback(data));
        }
    }

    // 事件监听器
    on(event, callback) {
        if (!this.events[event]) {
            this.events[event] = [];
        }
        this.events[event].push(callback);
    }

    // 工具函数：转义HTML
    escapeHtml(unsafe) {
        return unsafe
             .replace(/&/g, "&amp;")
             .replace(/</g, "&lt;")
             .replace(/>/g, "&gt;")
             .replace(/"/g, "&quot;")
             .replace(/'/g, "&#039;");
    }
}